package itsm.isperp.framework.quartz.listener;

import itsm.isperp.framework.quartz.domain.JobHistory;
import itsm.isperp.framework.quartz.executor.SpringBeanJobExecutorDetail;
import itsm.isperp.framework.quartz.repository.JobHistoryMapper;
import itsm.isperp.framework.quartz.service.IJobService;

import java.io.PrintWriter;
import java.io.StringWriter;
import java.util.Date;

import org.quartz.JobDataMap;
import org.quartz.JobDetail;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.quartz.JobListener;

/**
 */
public abstract class JobExecutionHistoryListener implements JobListener {

	protected JobHistoryMapper<JobHistory> jobHistoryMapper;

	private Date start;

	public JobExecutionHistoryListener(
			JobHistoryMapper<JobHistory> jobHistoryMapper) {
		this.jobHistoryMapper = jobHistoryMapper;
	}

	public abstract JobHistory getJobHistory();

	public String getName() {
		return "JobExecutionHistoryListener";
	}

	public void jobToBeExecuted(JobExecutionContext context) {
		this.start = new Date();
	}

	public void jobWasExecuted(JobExecutionContext context,
			JobExecutionException jobException) {
		JobDetail jobDetail = context.getJobDetail();
		if (!(jobDetail instanceof SpringBeanJobExecutorDetail)) {
			return;
		}
		JobDataMap map = jobDetail.getJobDataMap();
		if (!map.containsKey(IJobService.JOB_DEFINITION_ID)) {
			return;
		}
		//
		// Date end = new Date();
		// String exception = getExceptionStackMessage(jobException);
		// JobHistory history = getJobHistory();
		// history.setSuccessful(exception == null ? true : false);
		// if (exception != null) {
		// history.setMessage(exception.length() > 1500 ? exception.substring(
		// 0, 1500) : exception);
		// }
		// history.setEndDate(end);
		// history.setStartDate(start);
		// history.setId(UUID.randomUUID().toString());
		// history.setJobId(map.getString(IJobService.JOB_DEFINITION_ID));
		// this.jobHistoryMapper.save(history);
	}

	private String getExceptionStackMessage(JobExecutionException jobException) {
		if (jobException != null) {
			StringWriter sw = new StringWriter();
			PrintWriter pw = new PrintWriter(sw);
			jobException.printStackTrace(pw);
			return sw.toString();
		} else {
			return null;
		}
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * org.quartz.JobListener#jobExecutionVetoed(org.quartz.JobExecutionContext)
	 */
	@Override
	public void jobExecutionVetoed(JobExecutionContext context) {

	}
}
